package com.yunduo.filter;

import com.yunduo.common.JwtUtils;
import com.yunduo.common.YunDuoUtils;
import com.yunduo.entity.User;
import com.yunduo.service.UserService;
import com.yunduo.service.impl.UserServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Enumeration;

/**
 * shiro响应过滤器
 */
@Component
public class YunDuoFormAuthenticationFilter extends FormAuthenticationFilter{
    
    //shiro过滤器 拦截失败的请求，并再次登录
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        HttpServletRequest httpServletRequest = (HttpServletRequest)request;
        //处理前后端分离时自定义header会发出的options请求，进行一个过滤
        if("OPTIONS".equals(httpServletRequest.getMethod())){
            return true;
        }
        //检查是否存在token
        if(JwtUtils.checkToken(httpServletRequest)){
            User user = JwtUtils.getDataByJwtToken(httpServletRequest);
            String username=user.getName();
            String password=user.getPassword();
            AuthenticationToken authToken = new UsernamePasswordToken(username,password);
            YunDuoUtils.login(authToken);
            return true;
        }
        //未登录
        httpServletResponse.setStatus(200);
        httpServletResponse.setContentType("application/json;charset=utf-8");
        PrintWriter out = httpServletResponse.getWriter();
        JSONObject json = new JSONObject();
        json.put("code","403");
        json.put("msg","未登录");
        out.println(json);
        out.flush();
        out.close();
        return false;
    }

}
